/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import { Popconfirm, Space, message } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { getAreaBasePriceList, removeAreaBasePrice } from '@/services/jdk/areaPrice';
import { formatMoney } from '@/utils/utils';
import AddAreaPriceModal from '../addAreaPriceModal';

export const deliveryTypeMap = {
  '0': '平台运力',
  '1': '自运力',
};

const areaPriceColumns: ProColumns[] = [
  {
    title: '省市区',
    dataIndex: 'area_name_list',
    search: false,
    align: 'center',
    ellipsis: true,
    renderText: (area_name_list) => {
      return (
        <>
          {area_name_list && area_name_list.length > 0
            ? area_name_list.map((item: any) => {
                return <div key={item}>{item.join('')}</div>;
              })
            : '--'}
        </>
      );
    },
  },
  {
    title: '运力类型',
    dataIndex: 'limit_type',
    search: false,
    align: 'center',
    ellipsis: true,
    renderText: (limit_type) => {
      return deliveryTypeMap[`${limit_type}`];
    },
  },
  {
    title: '运力名称',
    dataIndex: 'brand_cn',
    search: false,
    align: 'center',
    ellipsis: true,
  },
  {
    title: '基础价(元)',
    dataIndex: 'base_price',
    search: false,
    align: 'center',
    ellipsis: true,
    renderText: (base_price) => {
      return formatMoney(base_price);
    },
  },
  {
    title: '设置时间',
    dataIndex: 'created_at',
    search: false,
    align: 'center',
    ellipsis: true,
    render: (_, record) => {
      return record.updated_at || record.created_at;
    },
  },
  {
    title: '设置人',
    dataIndex: 'operator',
    search: false,
    align: 'center',
    ellipsis: true,
  },
];

export const useAreaPrice = () => {
  const actionRef = useRef<ActionType>();
  const proFormRef = useRef<ProFormInstance>();
  const paginationRef = useRef<any>({});
  const [hasMore, setHasMore] = useState<any>();
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const reload = (v?: boolean) => {
    if (v) {
      paginationRef.current.setValues(1);
    }
    actionRef.current?.reload(v);
  };

  const handleRemove = async (_record: any) => {
    const { code, msg } = await removeAreaBasePrice({ id: _record.id });
    if (code == 0) {
      reload();
      message.success(msg);
    } else {
      message.error(msg);
    }
  };

  const columns: ProColumns[] = [
    ...areaPriceColumns,
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, record) => {
        return (
          <Space>
            <AddAreaPriceModal record={record} onRefresh={reload}>
              <a>编辑</a>
            </AddAreaPriceModal>
            <Popconfirm title='你确定移除吗？' onConfirm={handleRemove.bind(null, record)}>
              <a>移除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const queryTable = async () => {
    const { current: page, pageSize: size } = paginationRef.current.getValues();
    const formData = proFormRef.current?.getFieldsValue();
    const { code, data, msg } = await getAreaBasePriceList({ page, size, ...formData });
    setHasMore(data.list && data.list.length >= size);
    if (code == 0) {
      return {
        data: data.list || [],
        // total: 50
      };
    } else {
      message.error(msg);
      return {};
    }
  };

  return {
    actionRef,
    proFormRef,
    paginationRef,
    columns,
    queryTable,
    hasMore,
    winSize,
    reload,
  };
};
